package com.lagou.eduapi.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lagou.eduapi.service.FileService;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 *
 */
@Service
public class FileServiceImpl implements FileService {

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;
    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.secret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.bucket}")
    private String bucket;

    @Override
    public String upload(MultipartFile file) {
        System.out.println(endpoint);
        System.out.println(accessKeyId);
        System.out.println(accessKeySecret);
        System.out.println(bucket);
        try {
            // 创建OSSClient实例，很明显，给他用户的两个参数，以及域名节点信息，来初始化
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            // 上传文件流
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();
            // 生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = uuid+fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面

            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl+"/"+fileName; //类似于这样：2021/02/02/23fads85rj4hka01.mp4
            //分开就是2021/02/02，/23fads85rj4hka，01.mp4

            // 调用方法实现上传
            ossClient.putObject(bucket, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            // 上传之后文件路径
            // https://lagou-laosun.oss-cn-beijing.aliyuncs.com/01.jpg
            String url = "https://"+bucket+"."+endpoint+"/"+fileName;
            // 返回
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}